use std::io;
use log::{error, info, LevelFilter};
use simplelog::*;
use store::basic::add_word;
use store::sqlite;

#[tokio::main]
async fn main() {
    CombinedLogger::init(
        vec![
            TermLogger::new(LevelFilter::Info, Config::default(), TerminalMode::Mixed, ColorChoice::Auto),
        ]
    ).unwrap();
    info!("Initializing database...");
    let rb = sqlite::init("sqlite://./crates/store/db/word.db").await.expect("Initializing database Error...");
    info!("Initialized.");
    loop {
        print!(">");
        let input_word = read_word();
        let word_handler = tokio::spawn(net::query_word(input_word.clone()));
        let add_handler = tokio::spawn(add_word(rb.clone(), input_word.clone()));
        match word_handler.await.unwrap() {
            Ok(word) => {
                print!("{}", word);
                continue;
            }
            Err(e) => { error!("Query word error:{}",e) }
        }
        if let Err(e) = add_handler.await.unwrap(){
            error!("Add to database error:{}",e);
        }
    }
}

fn read_word() -> String {
    let mut input = String::new();
    // 读取用户输入的一行字符
    io::stdin().read_line(&mut input).expect("IO Error. Unable to read");
    input.trim().to_string()
}